/**
 * Copyright (c) 2012 Nokia Corporation. 
 */

package com.nokia.example.tictactoe.ui;

import java.io.IOException;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 * A custom button with a text that provides support (graphics) for both
 * positive and negative actions.
 */
public class Button {
	// Constants
	public static final int DEFAULT_WIDTH = 214;
	public static final int DEFAULT_HEIGHT = 37;
	
	// Members
	private final Font _font;
	private Image _normalImage = null;
	private Image _pressedImage = null;
	private String _text = null;
	private int _textX;
	private final int _textY;
	private boolean _pressed = false;
	private boolean _isNegative = false;
	
	/**
	 * Constructor.
	 * @param text
	 */
	public Button(String text) {
		_font = Font.getDefaultFont();
		_textY = (DEFAULT_HEIGHT - _font.getHeight()) / 2;
		setText(text);
		
		_isNegative = !_isNegative; // Force image loading
		setIsNegative(false);
	}
	
	/**
	 * 
	 * @param text
	 */
	public void setText(String text) {
		_text = text;
		
		if (_text != null && _text.length() > 0) {
			_textX = (DEFAULT_WIDTH - _font.stringWidth(_text)) / 2;
		}
	}
	
	/**
	 * 
	 * @param pressed
	 */
	public void setPressed(boolean pressed) {
		if (_pressed != pressed) {
			_pressed = pressed;
		}
	}
	
	/**
	 * 
	 * @param negative
	 */
	public void setIsNegative(boolean negative) {
		if (_isNegative != negative) {
			_isNegative = negative;
			
			_normalImage = null;
			_pressedImage = null;
			
			if (_isNegative) {
				try {
					_normalImage = Image.createImage("/graphics/button-red-normal.png");	
					_pressedImage = Image.createImage("/graphics/button-red-pressed.png");
				}
				catch (IOException e) {
					System.out.println("CustomButton::setIsNegative(): " + e.toString());
				}				
			}
			else {
				try {
					_normalImage = Image.createImage("/graphics/button-blue-normal.png");	
					_pressedImage = Image.createImage("/graphics/button-blue-pressed.png");
				}
				catch (IOException e) {
					System.out.println("CustomButton::setIsNegative(): " + e.toString());
				}
			}
		}
	}
	
	/** 
	 * @return The button width.
	 */
	public int width() {
		return DEFAULT_WIDTH;
	}
	
	/** 
	 * @return The button height.
	 */
	public int height() {
		return DEFAULT_HEIGHT;
	}
	
	/**
	 * 
	 * @param gc
	 */
	public void paint(Graphics gc, int x, int y) {
		if (!_pressed && _normalImage != null) {
			gc.drawImage(_normalImage, x,  y, Graphics.TOP | Graphics.LEFT);
		}
		else if (_pressedImage != null) {
			gc.drawImage(_pressedImage, x,  y, Graphics.TOP | Graphics.LEFT);
		}
		
		if (_text != null) {
			gc.setColor(0xffeeeeee);
			gc.drawString(_text, x + _textX, y + _textY,
						  Graphics.TOP | Graphics.LEFT);
		}				
	}
}
